<template>
  <div class="numBox">
    <div class="label">数量</div>
    <div class="numbox">
      <a @click="reduce" href="javascript:;">-</a>
      <!-- readonly:只读属性  value:数量初始值 -->
      <input type="text" readonly :value="modelValue">
      <a @click="add" href="javascript:;">+</a>
    </div>
  </div>
</template>

<script>
// 方案2:子组件有自己的数值
import { ref } from 'vue'
export default {
  name: 'numBox',
  props: {
    modelValue: {
      type: Number,
      required: true
    }
  },
  setup (props, { emit }) {
    // 数量增加
    const curNum = ref(props.modelValue)
    const add = () => {
      if (props.modelValue >= 0) {
        // const nextValue = props.modelValue + 1
        // 通知父组件把数量值+1
        // update:modelValue中已经集成方法,会自动把+1后的值传递给 v-model="num" 中的num
        // emit('update:modelValue', nextValue)
        // curNum.value = curNum.value + 1
        curNum.value += 1
        emit('update:modelValue', curNum.value)
      } else {
        alert('超过100件请联系客服')
      }
    }
    const reduce = () => {
      if (props.modelValue >= 1) {
        // const preValue = props.modelValue - 1
        // 通知父组件把数量值-1
        // update:modelValue 中已经集成方法,会自动把-1后的值传递给 v-model="num"中的num
        // emit('update:modelValue', preValue)
        curNum.value -= 1
        emit('update:modelValue', curNum.value)
      } else {
        alert('最小值为0')
      }
    }
    return {
      add,
      reduce
    }
  }
}
</script>

<style lang="less" scoped>
.numBox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
